import './index.less'
import { DownOutlined, EllipsisOutlined, PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable, TableDropdown } from '@ant-design/pro-components';
import { Button, Dropdown, Form, Input, Select, Space, Tag, message, Modal, Menu, Tree } from 'antd';
import { useEffect, useRef, useState } from 'react';
import { businessReportList } from '@/services/api/gng';
import { useAccess, Access } from 'umi';
import { request } from 'umi';
import EditCom from './edit';
import SelectTypesTree from '@/components/SelectTypesTree'
import { handleTreeList } from '@/utils'
const { Option } = Select;
export default (props: any) => {
    const requestsUrls = {
        list: "/sys/block/",
        delete: "/sys/block/",
        deleteBatch: "/sys/dict/deleteBatch",
        exportXlsUrl: "/sys/dict/exportXls",
        importExcelUrl: "/sys/dict/importExcel",
    };
    console.log(props.route.key);
    const actionRef = useRef<ActionType>();
    const editRef = useRef();
    const access = useAccess();
    const [form] = Form.useForm(); //搜索表单

    // const pageAuth = access[props.route.key] || {edit:true,delete:true,add:true};
    const pageAuth = { edit: true, delete: true, add: true };//权限暂时写死
    const businessTypedata = [
        { name: '客户发展', value: '1' },
        { name: '抄表收费', value: '2' },
        { name: '现场工单', value: '3' },
        { name: '增值服务', value: '4' },
    ]
    const deleteFn = (id) => {
        Modal.confirm({
            title: '确认删除？',
            content: '',
            onOk() {

                request(requestsUrls.delete + id, {
                    method: 'DELETE',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    data: {
                        id
                    }
                }).then((res) => {
                    message.success(res?.meta?.msg);
                    actionRef.current?.reload();
                })
            },
            onCancel() {
                console.log('Cancel')
            }
        })
    }
    const columns: ProColumns<businessReportItem>[] = [
        {
            dataIndex: 'index',
            valueType: 'indexBorder',
            width: 48,
        },
        {
            title: '组件名称',
            align: "center",
            key: 'blockName',
            dataIndex: 'blockName',
            hideInSearch: true,
        },
        {
            title: '组件适用设备端',
            align: "center",
            key: 'sourceType',
            dataIndex: 'sourceType',
            hideInSearch: true,
        },
        {
            title: '组件适用设备端',
            align: "center",
            key: 'showType',
            dataIndex: 'showType',
            hideInSearch: true,
            render: (txt, record, index) => {
                let showtype = record?.showType.split(',');
                return (<>{showtype.map((item) => <Tag color="blue">{['', '首页显示', '首页展开显示', '详情页显示', '详情日', '详情月', '详情年'][item]}</Tag>)}</>)
            }
        },
        {
            title: '排序',
            align: "center",
            key: 'sno',
            dataIndex: 'sno',
            hideInSearch: true,
        },
        {
            title: '描述',
            align: "center",
            key: 'remark',
            dataIndex: 'remark',
            hideInSearch: true,
        },

        // {
        //   title: '排序（升序）',
        //   align:"center",
        //   key:'sort',
        //   dataIndex: 'sort',
        //   hideInSearch: true,
        //   },

        {
            title: '操作',
            valueType: 'option',
            key: 'option',
            render: (text, record, _, action) => [
                pageAuth['edit'] ? (
                    <a
                        key="editable"
                        onClick={() => {
                            editRef.current?.init(record.blockId, record);
                        }}
                    >
                        编辑
                    </a>
                ) : (
                    <></>
                ),
                pageAuth['delete'] ? (
                    <a
                        key="editable"
                        onClick={() => {
                            deleteFn(record.blockId);
                        }}
                    >
                        删除
                    </a>
                ) : (
                    <></>
                ),
            ],
        },
    ];
    const [selectKey, setselectKey] = useState([]);
    const [menusTree, setmenusTree] = useState(null);
    const getMenus = async () => {
        const response: any = await request('/sys/menu/?sourceType=APP', {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
            },
            data: {

            },
        });
        let data = handleTreeList(response?.data)
        setmenusTree(data)
    }
    useEffect(() => {
        getMenus()
    }, [])
    useEffect(() => {
        if (selectKey) {
            actionRef.current?.reload();
        }

    }, [selectKey]);
    return (
        <div className='indexPage'>
            <div className='indexLeft'>
                {/* <Menu
                    onClick={(e) => {
                        setselectKey(e.key);
                    }}
                    selectedKeys={selectKey}
                >
                    {businessTypedata.map((item: any, i: number) => {
                        return (
                            <Menu.Item key={item.value}>
                                <div>
                                    <span style={{ marginLeft: '10px' }}>{item.name}</span>
                                </div>
                            </Menu.Item>
                        );
                    })}
                </Menu> */}
                {
                    menusTree && <Tree
                        switcherIcon={<DownOutlined />}
                        defaultExpandedKeys={['0-0-0']}
                        onSelect={(selectedKeys) => {
                            if (selectedKeys.length > 0) {
                                setselectKey(selectedKeys)
                            }
                            console.log(selectedKeys)
                        }}
                        selectedKeys={selectKey}
                        fieldNames={{ title: 'menuName', key: 'menuId' }}
                        treeData={menusTree}
                    />
                }

            </div>
            <div className='indexRight'>
                {
                    selectKey.length > 0 &&

                    <ProTable
                        actionRef={actionRef}
                        columns={columns}
                        search={false}
                        pagination={false}
                        params={form.getFieldsValue()}
                        // params 是需要自带的参数
                        // 这个参数优先级更高，会覆盖查询表单的参数
                        request={async (
                            // 第一个参数 params 查询表单和 params 参数的结合
                            // 第一个参数中一定会有 pageSize 和  current ，这两个参数是 antd 的规范
                            params: T & {
                                pageSize: number;
                                //current: number;
                            },
                            sort,
                            filter,
                        ) => {
                            const bussType = selectKey.length > 0 ? selectKey[0] : '';
                            // 这里需要返回一个 Promise,在返回之前你可以进行数据转化
                            // 如果需要转化参数可以在这里进行修改
                            const response: any = await request(requestsUrls.list + `?bussType=${bussType}&sourceType=`, {
                                method: 'GET',
                                headers: {
                                    'Content-Type': 'application/json',
                                },
                                data: {
                                    ...params,
                                    ...{
                                        pageNo: params.current,
                                        pageSize: params.pageSize,
                                        bussType: bussType
                                    }
                                },
                            });
                            return {
                                data: response?.data,
                                // success 请返回 true，
                                // 不然 table 会停止解析数据，即使有数据
                                success: true,
                                // 不传会使用 data 的长度，如果是分页一定要传
                                total: response?.data?.totalCount,
                                //message.success(res?.meta?.msg);
                            };
                        }}

                        toolBarRender={() => [
                            pageAuth['add'] && (
                                <Button
                                    key="button"
                                    icon={<PlusOutlined />}
                                    onClick={() => {
                                        editRef.current?.init();
                                    }}
                                    type="primary"
                                >
                                    新建
                                </Button>
                            ),
                        ]}
                    />
                }
                <EditCom
                    bussType={selectKey.length > 0 ? selectKey[0] : ''}
                    ref={editRef}
                    callback={() => {
                        actionRef.current?.reload();
                    }}
                />
            </div>
        </div>
    )
}